<?php
//
// +------------------------------------------------------------------------+
// | PHP Version 5.4                                                        |
// +------------------------------------------------------------------------+
// | Copyright (c) All rights reserved.                                     |
// +------------------------------------------------------------------------+
// | 世纪车来车往(北京）网络科技有限公司 版权所有！                         |
// | TEL:010-63732365  HOTLINE:400-6688-365  EMAIL:clcw@clcw.com.cn         |
// | $Revision: 1.0 $                                                       |
// +------------------------------------------------------------------------+
// | Author: songaimin@clcw.com.cn  Blog:http://blog.csdn.net/samxx8        |
// +------------------------------------------------------------------------+
//
namespace AuctionCore\Other;

use AuctionCore\System\AuctionException;
use AuctionCore\Other\CouponLog;

/**
 * 运营平台用代金券
 * @author       Eric Lee
 */
class BaseCoupon
{

    /**
     * 构造
     * @return   void
     */
    public function __construct()
    {
    }

    /**
     * 生成代金券
     * 返回一组代金券号。
     * @param    array $sets 生成设置
     * [代金券类型，数量，卷面金额，有效起始日期，有效结束日期]
     * @return   array
     */
    public function gen($sets)
    {
        if (empty($sets['type'])) {
            AuctionException::make_throw('800001');
        }
        if (empty($sets['amount'])) {
            AuctionException::make_throw('800002');
        }
        if (empty($sets['num'])) {
            AuctionException::make_throw('800003');
        }
        if (empty($sets['start_date'])) {
            AuctionException::make_throw('800004');
        }
        if (empty($sets['end_date'])) {
            AuctionException::make_throw('800005');
        }
        if (empty($sets['branch_company'])) {
            AuctionException::make_throw('800005');
        }
        M()->startTrans();
        //生成代金券类型
        $data = array();
        $data['type_name'] = $sets['type'];
        $data['amount'] = $sets['amount'];
        $data['branch_company'] = $sets['branch_company'];
        //查重
        $map = array();
        $map['type_name']  = $sets['type'];
        $map['amount']  = $sets['amount'];
        $map['branch_company'] = $sets['branch_company'];
        $coupon_type_id = M('coupon_type')->where($map)->getField('coupon_type_id');
        if (!$coupon_type_id) {
            $coupon_type_id = M('coupon_type')->add($data);
        }

        //生成代金券
        $coupon_ids = array();
        for ($i = 0; $i < $sets['num']; $i++) {
            $data = array();
            $data['emp_id'] = $sets['emp_id'];
            $data['coupon_type_id'] = $coupon_type_id;
            $data['start_date'] = $sets['start_date'];
            $data['end_date'] = $sets['end_date'];
            $data['createtime'] = date('Y-m-d H:i:s');
            $data['branch_company'] = $sets['branch_company'];
            $data['amount'] = $sets['amount'];
            $data['grant_type'] = 1;
            $id = M('coupon')->add($data);
            //修改
            M('coupon')->where("coupon_id='" . $id . "'")->save(array('coupon_no' => $id + 100000000));
            //
            $coupon_ids[] = $id;
        }
        if ($coupon_type_id && !in_array(false, $coupon_ids)) {
            M()->commit();
            $result = '成功';
        } else {
            M()->rollback();
            $result = '失败';
            if (empty($sets['end_date'])) {
                AuctionException::make_throw('800007');
            }
        }
        //日志
        $log = array('emp_id' => $sets['emp_id'], 'action' => '生成代金券 类型：' . $sets['type'] . ',数量:' . $sets['num'] . ' 结果：' . $result);
        \AuctionCore\System\SystemLog::add($log);
        return $coupon_ids;
    }

    /**
     * 发放代金券给车商
     */
    public function assign_coupon($data)
    {
        //
        if (!intval($data['coupon_type_id'])) {
            AuctionException::make_throw('800009');
        }
        if (!intval($data['dealer_id'])) {
            AuctionException::make_throw('500001');
        }
        if (intval($data['num']) < 1) {
            AuctionException::make_throw('800010');
        }

        $ret = $this->get_coupons(array('c.coupon_type_id' => array('eq', $data['coupon_type_id'])));
        if (count($ret) < $data['num']) {
            AuctionException::make_throw('800011');
        }
        $detail = $this->get_coupon_type_detail($data['coupon_type_id']);
        //启动事务
        M()->startTrans();
        $res = array();
        foreach ($ret as $key => $val) {
            //更改代金券状态
            $res[] = M('coupon')->where("coupon_id='" . $val['coupon_id'] . "'")->save(array('assign_status' => '1'));
            //记录到车商代金券表
            $info = array();
            $info['dealer_id'] = $data['dealer_id'];
            $info['coupon_id'] = $val['coupon_id'];
            $info['amount'] = $val['amount'];
            $info['coupon_no'] = $val['coupon_no'];
            $info['coupon_type_id'] = $data['coupon_type_id'];
            $info['coupon_type_name'] = $detail['type_name'];
            $info['start_date'] = $val['start_date'];
            $info['end_date'] = $val['end_date'];
            $info['createtime'] = date('Y-m-d H:i:s');
            $dc_res= M('dealer_coupon')->add($info);
            if($dc_res){
                //记录代金券发放日志
                $log = array(
                    'dealer_id' => $data['dealer_id'],
                    'coupon_id' => $val['coupon_id'],
                    'coupon_no' => $val['coupon_no'],
                    'cost_type' => "发放",
                    'occur_money' => $val['amount'],
                    'order_id' => 0,
                    'occur_type' => 0
                );
                CouponLog::add($log);
            }
            $res[] = $dc_res;


            if ($key == intval($data['num'] - 1)) {
                break;
            }

        }
        $flag = true;
        if (!in_array(false, $res)) {
            //提交事务
            M()->commit();
            $result = '代金券发放成功';
        } else {
            //事务回滚
            M()->rollback();
            $result = '代金券发放失败';
            $flag = false;
        }
        //日志
        $log = array(
            'emp_id' => $data['emp_id'],
            'action' => '发放代金券给车商' . $data['dealer_id'] . ' 类型ID：' . $data['coupon_type_id'] . ',数量:' . $data['num'] . ' ，实际发放数量' . $key . ' 结果：' . $result);
        \AuctionCore\System\SystemLog::add($log);
        return $flag;
    }

    /*
     * 获取有效代金券
     * */
    public function get_coupons($map = array(), $stat = false)
    {
        $map['c.assign_status'] = array('eq', '0');
        $map['c.end_date'] = array('egt', date('Y-m-d'));
        if ($stat) {
            $res = M('coupon')->alias('c')->where($map)->count();
        } else {
            $res = M('coupon')->alias('c')->field('c.*,ct.amount')->join(C('DB_PREFIX') . "coupon_type ct ON ct.coupon_type_id=c.coupon_type_id")
                ->where($map)->order('c.end_date')->select();
        }
        return $res;
    }

    /*
     * 获取所有代金券类型
     * @param type
     * */
    public function get_coupon_type($type = false,$branch_id=0)
    {
        $map = array();
        if($branch_id>0){
            $map['ct.branch_company'] = array('eq', $branch_id);
        }
        if (!$type) {//默认显示全部代金卷类型
            $res = M('coupon_type')->alias('ct')->where($map)->select();
        } else {//发放代金卷下拉菜单 ，过滤掉不能发放的类型
            $map['c.assign_status'] = array('eq', '0');
            $map['c.end_date'] = array('egt', date('Y-m-d'));
            $res = M('coupon_type')->alias('ct')->field("distinct(ct.type_name) as type_name,ct.amount,ct.coupon_type_id")
                ->join(C('DB_PREFIX') . "coupon c ON c.coupon_type_id=ct.coupon_type_id")->where($map)->select();
        }

        return $res;
    }


     /**
    *  获取指定发放类型的代金券类型
    */
    public function get_grant_coupon_type($grant_type,$branch_id=0){
        $map = array();
        if($branch_id>0){
            $map['ct.branch_company'] = array('eq', $branch_id);
        }
        if ($grant_type>0) {
             $map['c.grant_type'] = array('eq',$grant_type);
        }
       $res = M('coupon_type')->alias('ct')->field("ct.*")
                ->join(C('DB_PREFIX') . "coupon c ON c.coupon_type_id=ct.coupon_type_id")->where($map)->group('ct.coupon_type_id')->select();
        return $res;
    }


    /*
     * 获取代金券类型详情
     * */
    public function get_coupon_type_detail($type_id)
    {
        return M('coupon_type')->where("coupon_type_id='" . $type_id . "'")->find();
    }
}

?>